package com.rzjm.api.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.DeviceWeldingDao;
import com.rzjm.api.dao.FsrAssetsDao;
import com.rzjm.api.dao.FsrDeviceDao;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.FsrDeviceService;
import com.rzjm.api.service.ParameterService;
import com.rzjm.api.service.WxTemplateService;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.power.RequestSignUtils;
import com.rzjm.api.util.power.SmartPowerUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class FsrDeviceServiceImpl extends BaseServiceImpl<FsrDeviceDao, FsrDevice> implements FsrDeviceService {

    @Resource
    private FsrDeviceDao fsrDeviceDao;
    @Resource
    private DeviceWeldingDao deviceWeldingDao;
    @Resource
    private FsrAssetsDao fsrAssetsDao;
    @Resource
    private ParameterService parameterService;
    @Resource
    private WxTemplateService wxTemplateService;

    @Override
    public void getDeviceListByApi() {

        //菲舍尔的accessToken
        String accessToken = wxTemplateService.getAccessToken("","",2);

        JSONObject jsonObject = SmartPowerUtil.getAssets(accessToken);

        if(jsonObject!= null){
            boolean success = jsonObject.getBool("success");
            if(!success){
                String msg = jsonObject.getStr("msg");
                if(msg.equals("token invalid")){
                    accessToken = resetAccessToken();
                }
                jsonObject = SmartPowerUtil.getAssets(accessToken);
                success = jsonObject.getBool("success");
            }
//            System.out.println("资产数据： " + jsonObject.toString());
            if(success){
                JSONArray result = jsonObject.getJSONArray("result");
                if(result.size() > 0){
                    for (int i = 0;i < result.size() ; i++){
                        //父资产
                        JSONObject asset = (JSONObject)result.get(i);
                        addAssets(asset,accessToken);
                        // 子资产
                        recursionData(asset,accessToken);
                    }
                }
            }
        }
    }

    @Override
    public void getDeviceListByAssId(String assetId) {
        //菲舍尔的accessToken
        String accessToken = wxTemplateService.getAccessToken("","",2);
        JSONObject jsonObject = SmartPowerUtil.getDeviceList(assetId, accessToken);
        if(jsonObject!= null){
            boolean success = jsonObject.getBool("success");
            if(!success){
                String msg = jsonObject.getStr("msg");
                if(msg.equals("token invalid")){
                    accessToken = resetAccessToken();
                }
                jsonObject = SmartPowerUtil.getDeviceList(assetId, accessToken);
                success = jsonObject.getBool("success");
            }
            if(success){
                JSONArray result = jsonObject.getJSONArray("result");
                if(result.size() > 0){
                    for (int i = 0; i < result.size(); i++){

                        JSONObject deviceJson = (JSONObject)result.get(i);

                        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
                        qw.eq("id",deviceJson.getStr("id"));
                        qw.last("limit 1");

                        int powerStatus = 0;
                        String status = deviceJson.getStr("status");
                        JSONArray jsonArrayStatus = JSONUtil.parseArray(JSONUtil.toJsonStr(status));
                        for (int j = 0; j < jsonArrayStatus.size(); j++){
                            JSONObject statusJson = (JSONObject)jsonArrayStatus.get(j);
                            if(statusJson != null){
                                String code = statusJson.getStr("code");
                                boolean value = statusJson.getBool("value");

                                if(code.equals("switch")){
                                    if(value){
                                        powerStatus = 1;
                                    }else{
                                        powerStatus = 0;
                                    }
                                }
                            }
                        }

                        FsrDevice fsrDevice = fsrDeviceDao.selectOne(qw);
                        if(fsrDevice == null){
                            fsrDevice = new FsrDevice();
                            fsrDevice.setAssetId(assetId);
                            fsrDevice.setId(deviceJson.getStr("id"));
                            fsrDevice.setDeviceId(0);
                            fsrDevice.setCategory(deviceJson.getStr("category"));
                            fsrDevice.setIcon(deviceJson.getStr("icon"));
                            fsrDevice.setName(deviceJson.getStr("name"));
                            fsrDevice.setOnlineState(deviceJson.getBool("online")?1:0);
                            if(fsrDevice.getOnlineState() == 1){
                                fsrDevice.setLastOnlineTime(new Date());
                            }
                            fsrDevice.setProductId(deviceJson.getStr("product_id"));
                            fsrDevice.setProductName(deviceJson.getStr("product_name"));
                            fsrDevice.setUuid(deviceJson.getStr("uuid"));
                            fsrDevice.setCreateTime(new Date());
                            fsrDevice.setPowerCodeState(powerStatus);
                            fsrDevice.setIsSelf(1);
                            fsrDevice.setLastWarnTime(new Date());
                            fsrDeviceDao.insert(fsrDevice);
                        }else{
                            fsrDevice.setAssetId(assetId);
                            fsrDevice.setCategory(deviceJson.getStr("category"));
                            fsrDevice.setName(deviceJson.getStr("name"));
                            fsrDevice.setOnlineState(deviceJson.getBool("online") ? 1 : 0);
                            if(fsrDevice.getOnlineState() == 1){
                                fsrDevice.setLastOnlineTime(new Date());
                            }
                            fsrDevice.setIsSelf(1);
                            fsrDevice.setPowerCodeState(powerStatus);
                            fsrDeviceDao.updateById(fsrDevice);
                        }

//                                System.out.println(deviceJson.getStr("name") + " " + (powerStatus == 1 ? "开启" : "关闭"));

                        //上电之后处理  断电判断
                        if(fsrDevice.getOnlineState() == 1){
                            DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                            if(device != null){
                                //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1) {
                                    //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                                    if(
                                            (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                                    || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)
                                                    || (device.getShopId() == 0 && fsrDevice.getPowerCodeState() == 1)
                                    ){
                                        commandOp(fsrDevice, 0);
                                        device.setUseState(0);
                                        deviceWeldingDao.updateById(device);
//                                                fsrDevice.setPowerCodeState(0);
//                                                fsrDeviceDao.updateById(fsrDevice);
//                                                System.out.println("===========11111111============");
//                                                System.out.println("焊机 ，执行关闭   执行时间： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                    }
                                }
                            }else{
                                if(fsrDevice.getPowerCodeState() == 1){
                                    commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========22222222============");
//                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                }
                            }
                        } else {//设备断电的，需要把已申请的记录状态给弄成未使用状态
                            DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                            if(device != null) {
                                //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1 && fsrDevice.getPowerCodeState() == 1) {
                                    commandOp(fsrDevice, 0);
                                    device.setUseState(3);//已断电
                                    deviceWeldingDao.updateById(device);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========33333333============");
//                                            System.out.println("设备断电，直接修改设备的使用状态为未使用， " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                }
                            }else{
                                if(fsrDevice.getPowerCodeState() == 1){
                                    commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========4444444444============");
//                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void getDeviceStatusByApi() {
        //菲舍尔的accessToken
        String accessToken = wxTemplateService.getAccessToken("","",2);
        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
        qw.eq("is_self", 1);
//        qw.eq("id", "6c7f04c1e848e4384b4i3b");
//        qw.eq("is_working", 1);
        qw.last("limit 30");
        qw.orderByAsc("last_update_time");
        List<FsrDevice> listDevice = fsrDeviceDao.selectList(qw);
        for (FsrDevice fsrDevice : listDevice){
            QueryWrapper<FsrAssets> qwAss = new QueryWrapper<>();
            qwAss.eq("asset_id", fsrDevice.getAssetId());
            qwAss.last("limit 1");
            FsrAssets assets = fsrAssetsDao.selectOne(qwAss);
            if(assets != null){
                JSONObject jsonObject = SmartPowerUtil.getDeviceStatus(fsrDevice.getId(), accessToken);
                if(assets.getIsShowLog() == 1){
                    System.out.println("资产设备列表：" + assets.getAssetId() + " ==== " + jsonObject.toString());
                }
                if(jsonObject!= null){
                    boolean success = jsonObject.getBool("success");
                    if(success){
                        JSONArray result = jsonObject.getJSONArray("result");
                        if(result.size() > 0){
                            for (int i = 0; i < result.size(); i++){
                                JSONObject deviceJson = (JSONObject)result.get(i);

                                int powerStatus = 0;
                                String status = deviceJson.getStr("status");
                                JSONArray jsonArrayStatus = JSONUtil.parseArray(JSONUtil.toJsonStr(status));
                                for (int j = 0; j < jsonArrayStatus.size(); j++){
                                    JSONObject statusJson = (JSONObject)jsonArrayStatus.get(j);
                                    if(statusJson != null){
                                        String code = statusJson.getStr("code");
                                        boolean value = statusJson.getBool("value");
                                        if(code.equals("switch")){
//                                            System.out.println("statusJson: " + statusJson);
                                            if(value){
                                                powerStatus = 1;
                                            }else{
                                                powerStatus = 0;
                                            }
                                        }
                                    }
                                }

                                fsrDevice.setIsSelf(assets.getIsSelf());
                                fsrDevice.setPowerCodeState(powerStatus);
                                if(powerStatus == 1){
                                    System.out.println("" + fsrDevice.getName());
                                    fsrDevice.setOnlineState(1);
                                    fsrDevice.setLastOnlineTime(new Date());
                                }else{
//                                    fsrDevice.setOnlineState(0);
                                }

                                System.out.println(fsrDevice.getName() + " " + (powerStatus == 1 ? "开启" : "关闭"));

                                //上电之后处理  断电判断
                                if(fsrDevice.getOnlineState() == 1){
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null){
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1) {
                                            //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                                            if(
                                                    (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                                            || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)
                                                            || (device.getShopId() == 0&& fsrDevice.getPowerCodeState() == 1)
                                            ){
                                                commandOp(fsrDevice, 0);
                                                device.setUseState(0);
                                                deviceWeldingDao.updateById(device);
//                                                fsrDevice.setPowerCodeState(0);
//                                                fsrDeviceDao.updateById(fsrDevice);
//                                                System.out.println("焊机 ，执行关闭   执行时间： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                            }
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                } else {//设备断电的，需要把已申请的记录状态给弄成未使用状态
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null) {
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1 && fsrDevice.getPowerCodeState() == 1) {
                                            commandOp(fsrDevice, 0);
                                            device.setUseState(3);//已断电
                                            deviceWeldingDao.updateById(device);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("设备断电，直接修改设备的使用状态为未使用， " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    fsrDevice.setLastUpdateTime(new Date());
                    fsrDeviceDao.updateById(fsrDevice);
                }
            }
        }
    }


    @Override
    public void getDeviceOnlineStatusByApi() {
        //菲舍尔的accessToken
        String accessToken = wxTemplateService.getAccessToken("","",2);
        QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
        qw.eq("is_self", 1);
//        qw.eq("id", "6c7f04c1e848e4384b4i3b");
        qw.last("limit 30");
        qw.orderByAsc("last_online_check_time");
        List<FsrDevice> listDevice = fsrDeviceDao.selectList(qw);
        for (FsrDevice fsrDevice : listDevice){
            QueryWrapper<FsrAssets> qwAss = new QueryWrapper<>();
            qwAss.eq("asset_id", fsrDevice.getAssetId());
            qwAss.last("limit 1");
            FsrAssets assets = fsrAssetsDao.selectOne(qwAss);
            if(assets != null) {
                JSONObject jsonObject = SmartPowerUtil.getDeviceDetail(fsrDevice.getId(), accessToken);
                if(assets.getIsShowLog() == 1){
                    System.out.println("资产设备列表：" + assets.getAssetId() + " ==== " + jsonObject.toString());
                }
                //获取单个设备在线详情：{"msg":"云开发企业版订阅已到期，无权限。","code":2.8841002E7,"tid":"4f0c84b2677411ef8a65e283003eef7e","t":1.725093471242E12,"success":false}
                if (jsonObject != null) {
                    boolean success = jsonObject.getBool("success");
                    if (success) {
                        JSONObject result = jsonObject.getJSONObject("result");
                        if (result != null) {
                            boolean online = result.getBool("online");
                            fsrDevice.setOnlineState(online ? 1 : 0);
                            if (online) {
                                fsrDevice.setLastOnlineTime(new Date());
                            } else {
                                fsrDevice.setLastOfflineTime(new Date());
                            }
                        }
                    }
                }
                fsrDevice.setLastOnlineCheckTime(new Date());
                fsrDeviceDao.updateById(fsrDevice);
            }
        }
    }

    /**
     *  递归遍历
     */
    private void recursionData(JSONObject asset, String accessToken){
        // 子资产
        JSONArray sub_assets_1 = asset.getJSONArray("sub_assets");
        if(sub_assets_1.size() > 0){
            for (int i = 0;i < sub_assets_1.size() ; i++){
                JSONObject sub_asset_1 = (JSONObject) sub_assets_1.get(i);
                addAssets(sub_asset_1,accessToken);
                JSONArray sub_assets_2 = sub_asset_1.getJSONArray("sub_assets");
                if(sub_assets_2.size() > 0){
                    recursionData(sub_asset_1,accessToken);
                }
            }
        }
    }

    private void addAssets(JSONObject asset,String accessToken){
        if(asset != null){
            String asset_id = asset.getStr("asset_id");
            String parent_asset_id = asset.getStr("parent_asset_id");
            String asset_full_name = asset.getStr("asset_full_name");
            Integer level = asset.getInt("level");

            //筒仓节点
            String master_parent_id =  "159497020";

            QueryWrapper<FsrAssets> qwAsset = new QueryWrapper<>();
            qwAsset.eq("asset_id",asset_id);
            qwAsset.last("limit 1");
            FsrAssets assets = fsrAssetsDao.selectOne(qwAsset);
            if(assets == null){
                assets = new FsrAssets();
                assets.setDeviceCount(0);
                assets.setLevel(level);
                assets.setAssetId(asset_id);
                assets.setParentId(parent_asset_id);
                assets.setFsrAssetName(asset_full_name);
                assets.setIsSelf(0);
                if(asset_id.equals(master_parent_id) || parent_asset_id.equals(master_parent_id)){
                    assets.setIsSelf(1);
                }else{
                    if(!parent_asset_id.equals("-1")){
                        QueryWrapper<FsrAssets> qwAssetParent = new QueryWrapper<>();
                        qwAssetParent.eq("asset_id", parent_asset_id);
                        qwAssetParent.last("limit 1");
                        FsrAssets assetsParent = fsrAssetsDao.selectOne(qwAssetParent);
                        if(assetsParent != null){
                            assets.setIsSelf(assetsParent.getIsSelf());
                        }
                    }
                }
                fsrAssetsDao.insert(assets);
            }
//            else{
//                assets.setLevel(level);
//                assets.setParentId(parent_asset_id);
//                assets.setFsrAssetName(asset_full_name);
//                assets.setIsSelf(0);
//                if(asset_id.equals(master_parent_id) || parent_asset_id.equals(master_parent_id)){
//                    assets.setIsSelf(1);
//                }else{
//                    if(!parent_asset_id.equals("-1")){
//                        QueryWrapper<FsrAssets> qwAssetParent = new QueryWrapper<>();
//                        qwAssetParent.eq("asset_id", parent_asset_id);
//                        qwAssetParent.last("limit 1");
//                        FsrAssets assetsParent = fsrAssetsDao.selectOne(qwAssetParent);
//                        if(assetsParent != null){
//                            assets.setIsSelf(assetsParent.getIsSelf());
//                        }
//                    }
//                }
//                fsrAssetsDao.updateById(assets);
//            }

            if(StrUtil.isNotEmpty(asset_id) && assets.getIsSelf() == 1){
                JSONObject jsonObject = SmartPowerUtil.getDeviceList(asset_id, accessToken);
                if(jsonObject!= null){
                    boolean success = jsonObject.getBool("success");
                    if(!success){
                        String msg = jsonObject.getStr("msg");
                        if(msg.equals("token invalid")){
                            accessToken = resetAccessToken();
                        }
                        jsonObject = SmartPowerUtil.getDeviceList(asset_id, accessToken);
                        success = jsonObject.getBool("success");
                    }
                    if(success){
                        JSONArray result = jsonObject.getJSONArray("result");
                        if(result.size() > 0){
                            for (int i = 0; i < result.size(); i++){

                                JSONObject deviceJson = (JSONObject)result.get(i);

                                QueryWrapper<FsrDevice> qw = new QueryWrapper<>();
                                qw.eq("id",deviceJson.getStr("id"));
                                qw.last("limit 1");

                                int powerStatus = 0;
                                String status = deviceJson.getStr("status");
                                JSONArray jsonArrayStatus = JSONUtil.parseArray(JSONUtil.toJsonStr(status));
                                for (int j = 0; j < jsonArrayStatus.size(); j++){
                                    JSONObject statusJson = (JSONObject)jsonArrayStatus.get(j);
                                    if(statusJson != null){
                                        String code = statusJson.getStr("code");
                                        boolean value = statusJson.getBool("value");

                                        if(code.equals("switch")){
                                            if(value){
                                                powerStatus = 1;
                                            }else{
                                                powerStatus = 0;
                                            }
                                        }
                                    }
                                }

                                FsrDevice fsrDevice = fsrDeviceDao.selectOne(qw);
                                if(fsrDevice == null){
                                    fsrDevice = new FsrDevice();
                                    fsrDevice.setAssetId(asset_id);
                                    fsrDevice.setId(deviceJson.getStr("id"));
                                    fsrDevice.setDeviceId(0);
                                    fsrDevice.setCategory(deviceJson.getStr("category"));
                                    fsrDevice.setIcon(deviceJson.getStr("icon"));
                                    fsrDevice.setName(deviceJson.getStr("name"));
                                    fsrDevice.setOnlineState(deviceJson.getBool("online")?1:0);
                                    if(fsrDevice.getOnlineState() == 1){
                                        fsrDevice.setLastOnlineTime(new Date());
                                    }
                                    fsrDevice.setProductId(deviceJson.getStr("product_id"));
                                    fsrDevice.setProductName(deviceJson.getStr("product_name"));
                                    fsrDevice.setUuid(deviceJson.getStr("uuid"));
                                    fsrDevice.setCreateTime(new Date());
                                    fsrDevice.setPowerCodeState(powerStatus);
                                    fsrDevice.setIsSelf(assets.getIsSelf());
                                    fsrDevice.setLastWarnTime(new Date());
                                    fsrDeviceDao.insert(fsrDevice);
                                }else{
                                    fsrDevice.setAssetId(assets.getId());
                                    fsrDevice.setCategory(deviceJson.getStr("category"));
                                    fsrDevice.setName(deviceJson.getStr("name"));
                                    fsrDevice.setAssetId(asset_id);
                                    fsrDevice.setOnlineState(deviceJson.getBool("online") ? 1 : 0);
                                    if(fsrDevice.getOnlineState() == 1){
                                        fsrDevice.setLastOnlineTime(new Date());
                                    }
                                    fsrDevice.setIsSelf(assets.getIsSelf());
                                    fsrDevice.setPowerCodeState(powerStatus);
                                    fsrDeviceDao.updateById(fsrDevice);
                                }

//                                System.out.println(deviceJson.getStr("name") + " " + (powerStatus == 1 ? "开启" : "关闭"));

                                //上电之后处理  断电判断
                                if(fsrDevice.getOnlineState() == 1){
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null){
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1) {
                                            //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                                            if(
                                                    (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                                    || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)
                                                    || (device.getShopId() == 0 && fsrDevice.getPowerCodeState() == 1)
                                            ){
                                                commandOp(fsrDevice, 0);
                                                device.setUseState(0);
                                                deviceWeldingDao.updateById(device);
//                                                fsrDevice.setPowerCodeState(0);
//                                                fsrDeviceDao.updateById(fsrDevice);
//                                                System.out.println("===========11111111============");
//                                                System.out.println("焊机 ，执行关闭   执行时间： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                            }
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========22222222============");
//                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                } else {//设备断电的，需要把已申请的记录状态给弄成未使用状态
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null) {
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1 && fsrDevice.getPowerCodeState() == 1) {
                                            commandOp(fsrDevice, 0);
                                            device.setUseState(3);//已断电
                                            deviceWeldingDao.updateById(device);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========33333333============");
//                                            System.out.println("设备断电，直接修改设备的使用状态为未使用， " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("===========4444444444============");
//                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    @Override
    public String resetAccessToken() {

        String access_token = "";
        Parameter parameter = parameterService.findById(1);
        if(parameter!= null) {//
            JSONObject jsonObject = RequestSignUtils.getAccessToken();
            if (jsonObject != null) {
                boolean code = jsonObject.getBool("success");
                if (code) {
                    access_token = jsonObject.getJSONObject("result").getStr("access_token");
                    String refresh_token = jsonObject.getJSONObject("result").getStr("refresh_token");
                    parameter.setFsrAccessToken(access_token);
                    parameter.setFsrRefreshToken(refresh_token);
                    parameter.setFsrLastTokenTime(DateUtil.getAfterSecondsByOld(new Date(), 7000));
                    parameter.setFsrRefreshTime(DateUtil.getAfterSecondsByOld(new Date(), 7000));
                    parameterService.updateById(parameter);
                }
            }
        }
        return access_token;
    }

    @Override
    public void initSearchDeviceStatus(String id) {

        //菲舍尔的accessToken
        String accessToken = wxTemplateService.getAccessToken("","",2);
        FsrDevice fsrDevice = fsrDeviceDao.selectById(id);
        if(fsrDevice != null){
            QueryWrapper<FsrAssets> qwAss = new QueryWrapper<>();
            qwAss.eq("asset_id", id);
            qwAss.last("limit 1");
            FsrAssets assets = fsrAssetsDao.selectOne(qwAss);
            if(assets != null){
                JSONObject jsonObject = SmartPowerUtil.getDeviceStatus(fsrDevice.getId(), accessToken);
                if(assets.getIsShowLog() == 1){
                    System.out.println("资产设备列表：" + assets.getAssetId() + " ==== " + jsonObject.toString());
                }
                if(jsonObject!= null){
                    boolean success = jsonObject.getBool("success");
                    if(success){
                        JSONArray result = jsonObject.getJSONArray("result");
                        if(result.size() > 0){
                            for (int i = 0; i < result.size(); i++){
                                JSONObject deviceJson = (JSONObject)result.get(i);

                                int powerStatus = 0;
                                String status = deviceJson.getStr("status");
                                JSONArray jsonArrayStatus = JSONUtil.parseArray(JSONUtil.toJsonStr(status));
                                for (int j = 0; j < jsonArrayStatus.size(); j++){
                                    JSONObject statusJson = (JSONObject)jsonArrayStatus.get(j);
                                    if(statusJson != null){
                                        String code = statusJson.getStr("code");
                                        boolean value = statusJson.getBool("value");
                                        if(code.equals("switch")){
//                                            System.out.println("statusJson: " + statusJson);
                                            if(value){
                                                powerStatus = 1;
                                            }else{
                                                powerStatus = 0;
                                            }
                                        }
                                    }
                                }

                                fsrDevice.setIsSelf(assets.getIsSelf());
                                fsrDevice.setPowerCodeState(powerStatus);
                                if(powerStatus == 1){
                                    System.out.println("" + fsrDevice.getName());
                                    fsrDevice.setOnlineState(1);
                                    fsrDevice.setLastOnlineTime(new Date());
                                }else{
//                                    fsrDevice.setOnlineState(0);
                                }

                                System.out.println(fsrDevice.getName() + " " + (powerStatus == 1 ? "开启" : "关闭"));

                                //上电之后处理  断电判断
                                if(fsrDevice.getOnlineState() == 1){
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null){
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1) {
                                            //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                                            if(
                                                    (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                                            || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)
                                                            || (device.getShopId() == 0&& fsrDevice.getPowerCodeState() == 1)
                                            ){
                                                commandOp(fsrDevice, 0);
                                                device.setUseState(0);
                                                deviceWeldingDao.updateById(device);
//                                                fsrDevice.setPowerCodeState(0);
//                                                fsrDeviceDao.updateById(fsrDevice);
//                                                System.out.println("焊机 ，执行关闭   执行时间： " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                            }
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                } else {//设备断电的，需要把已申请的记录状态给弄成未使用状态
                                    DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
                                    if(device != null) {
                                        //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                                        if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1 && fsrDevice.getPowerCodeState() == 1) {
                                            commandOp(fsrDevice, 0);
                                            device.setUseState(3);//已断电
                                            deviceWeldingDao.updateById(device);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                                            System.out.println("设备断电，直接修改设备的使用状态为未使用， " + DateUtil.getTime()+ "设备id： " + fsrDevice.getId());
                                        }
                                    }else{
                                        if(fsrDevice.getPowerCodeState() == 1){
                                            commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
                                            System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    fsrDevice.setLastUpdateTime(new Date());
                    fsrDeviceDao.updateById(fsrDevice);
                }
            }
        }
    }

    @Override
    public void testDevice(FsrDevice fsrDevice) {

        //上电之后处理  断电判断
        if(fsrDevice.getOnlineState() == 1){
            DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
            if(device != null){
                //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1) {
                    //使用状态 0 - 未使用  1 - 申请中 2 - 审核通过使用中
                    if(
                            (device.getUseState() == 2 && new Date().getTime() > device.getUseEndTime().getTime())
                                    || (device.getUseState() == 0 && fsrDevice.getPowerCodeState() == 1)
                                    || (device.getShopId() == 0 && fsrDevice.getPowerCodeState() == 1)
                    ){
                        commandOp(fsrDevice, 0);
                        device.setUseState(0);
                        deviceWeldingDao.updateById(device);
//                                                fsrDevice.setPowerCodeState(0);
//                                                fsrDeviceDao.updateById(fsrDevice);
//                        System.out.println("焊机，执行关闭   执行时间： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                    }
                }
            }else{
                if(fsrDevice.getPowerCodeState() == 1){
                    commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                    System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                }
            }
        } else {//设备断电的，需要把已申请的记录状态给弄成未使用状态
            DeviceWelding device = deviceWeldingDao.selectById(fsrDevice.getDeviceId());
            if(device != null) {
                //使用中的 时候，断电重启之后 超过申请的结束时间  就执行关闸
                if(device.getIsHasBreaker() == 1 && fsrDevice.getIsSelf() == 1 && fsrDevice.getPowerCodeState() == 1) {
                    commandOp(fsrDevice, 0);
                    device.setUseState(3);//已断电
                    deviceWeldingDao.updateById(device);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
                    System.out.println("设备断电，直接修改设备的使用状态为未使用， " + DateUtil.getTime());
                }
            }else{
                if(fsrDevice.getPowerCodeState() == 1){
                    commandOp(fsrDevice, 0);
//                                            fsrDevice.setPowerCodeState(0);
//                                            fsrDeviceDao.updateById(fsrDevice);
//                    System.out.println("设备未绑定企业设备，关闭： " + DateUtil.getTime() + "设备id： " + fsrDevice.getId());
                }
            }
        }
    }

    @Override
    public int commandOp(FsrDevice device,int openStatus) {
        String accessToken = wxTemplateService.getAccessToken("","",2);
        JSONObject jsonObject = SmartPowerUtil.deviceCommand(device.getId(), accessToken,openStatus == 1 ? true : false);
        if(jsonObject != null) {
            boolean success = jsonObject.getBool("success");
            if (!success) {
                String msg = jsonObject.getStr("msg");
                if (msg.equals("token invalid")) {
                    accessToken = resetAccessToken();
                }
                jsonObject = SmartPowerUtil.deviceCommand(device.getId(), accessToken,openStatus == 1 ? true : false);
                success = jsonObject.getBool("success");
            }
            if(success){

                if(openStatus == 1){
                    device.setIsWorking(1);
                }else{
                    device.setIsWorking(0);
                }
                return 1;
            }
        }

        return 1;
    }
}
